<template>
  <j-modal
    :title='title'
    width='70%'
    :visible='visible'
    :confirmLoading='confirmLoading'
    switchFullscreen
    @ok='handleOk'
    @cancel='handleCancel'
    cancelText='关闭'>
    <template slot='footer'>
      <a-button @click='handleCancel'>取消</a-button>
      <a-button @click='handleOk' type='primary' v-if='!disableSubmit'>确认</a-button>
    </template>

    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-row style='width: 100%;'>
          <!--          政策名称-->
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              hasFeedback
              label='政策名称'>
              <a-input v-decorator="['saasid', {}]" hidden />
              <a-input v-decorator="['proCode', {}]" hidden />
              <a-input :disabled='disableSubmit' placeholder='请输入政策名称'
                       v-decorator="['proName', { rules: [{ required: true, message: '请输入政策名称' }] }]" />
            </a-form-item>
          </a-col>
          <!--          有效时间-->
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              hasFeedback
              label='有效时间'>
              <a-range-picker
                format='YYYY-MM-DD' valueFormat='YYYY-MM-DD'
                :disabled='disableSubmit'
                v-decorator="['date',{rules: [{ required: true, message: '有效时间' }]}]"
                @change='dateChange'
              />
            </a-form-item>
          </a-col>
          <!--          状态-->
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              hasFeedback
              label='状态'>
              <a-select :disabled='disableSubmit'
                        v-decorator="['status',{rules: [{ required: true, message: '请选择状态' }]}]" placeholder='请选择状态'>
                <a-select-option value='009'>
                  启用
                </a-select-option>
                <a-select-option value='003'>
                  禁用
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--          是否首单享受-->
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='是否首单享受'>
              <a-radio-group :disabled='disableSubmit'
                             v-decorator="['isFirst',{rules: [{ required: true, message: '是否首单享受' }],initValue:1}]">
                <a-radio :value='1'>
                  是
                </a-radio>
                <a-radio :value='0'>
                  否
                </a-radio>
              </a-radio-group>

            </a-form-item>
          </a-col>
          <!--          未带走货物流向-->
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              hasFeedback
              label='未带走货物流向'>
              <cn-dict-select-tag :options="{value:'dictDataCode',label:'dictDataDesc'}"
                                 :triggerChange='true'
                                 dictCode='is_to_go'
                                 @change='e => goodsChange(e)'
                                 v-decorator="['isToDo',{rules: [{ required: true, message: '请选择未带走货物流向' }]}]"
                                 placeholder='未带走货物流向'
                                 :disabled='disableSubmit'
              />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24' v-if='istodo'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='商品名称'
            >
              <a-input-search placeholder='请选择商品'
                              v-decorator="['productName',{rules: [{ required: true, message: '请选择货补商品' }]}]"
                              readOnly :disabled='disableSubmit' enter-button @search="productSearch('product')" />
              <a-input type='hidden' v-decorator="['productCode']" />
            </a-form-item>
          </a-col>
          <!--          详细内容-->
          <a-col :md='24' :sm='24'>
            <a-col :md='8' :sm='24'>
              <a-form-item
                :labelCol='labelCol'
                :wrapperCol='wrapperCol'
                hasFeedback
                label='详细内容'>
                <a-input :disabled='disableSubmit' type='textarea' :maxLength='500' placeholder='请输入详细内容'
                         v-decorator="['remarks']" />
              </a-form-item>
            </a-col>
          </a-col>


          <a-col :span='24'>
            <div class='items-title' style=''>
              <span style='margin-right: 16px'>政策规则</span>
            </div>
          </a-col>

          <a-col :md='24' :sm='24'>
            <div style='padding:0 24px;'>
              <a-col :md='16' :sm='24'>
                <span style='display: flex; align-items: center ;margin-bottom: 12px'>
                  <div style=''>本品：</div>
                    <j-select-product v-if='!disableSubmit' selectButtonText='添加本品' :inputs='false' searchIcon=''
                                      @select="(row)=>productSelect(row,'bpList',1)" />
                </span>
              </a-col>
              <a-col :md='18' :sm='24'>
                <a-table
                  ref='table'
                  size='middle'
                  class='Table'
                  bordered
                  rowKey='code'
                  :columns='bpColumns'
                  :dataSource='bpList'
                  :pagination='ipagination'
                  :loading='loading'
                  @change="(e1,e2,e3) =>handleTableChange(e1,e2,e3,'1')"
                >
                      <span slot='action' v-if='!disableSubmit' slot-scope='text, record,index'>
                        <a @click.stop="productDelete(index,'bpList')">删除</a>
                      </span>
                </a-table>
              </a-col>
            </div>
          </a-col>

          <a-col :md='24' :sm='24'>
            <div style='padding:0 24px;'>
              <a-col :md='16' :sm='24'>
                <span style='display: flex; align-items: center ;margin: 12px 0'>
                  <div style=''>赠品：</div>
                  <j-select-product v-model='custValue' selectButtonText='添加赠品' v-if='!disableSubmit' :inputs='false'
                                    searchIcon='' @select="(row)=>productSelect(row,'zpList',2)" />
                  <div style='font-size: 12px;margin-left: 24px;color: #999;'>注:同一标识符的带走比例共用,不会重复计入百分比总和。</div>
                </span>
              </a-col>
              <a-col :md='18' :sm='24'>
                <a-table
                  ref='table'
                  size='middle'
                  class='Table'
                  bordered
                  rowKey='code'
                  :columns='zpColumns'
                  :dataSource='zpList'
                  :pagination='ipagination1'
                  :loading='loading'
                  @change="(e1,e2,e3) =>handleTableChange(e1,e2,e3,'2')"
                >
                  <template slot='isSpirit' slot-scope='t,r,index'>
                    <a-select v-model='t' :default-value='0' @change='e => selectCH(e,index)'>
                      <a-select-option :value='1'>
                        是
                      </a-select-option>
                      <a-select-option :value='0'>
                        否
                      </a-select-option>
                    </a-select>
                  </template>
                  <template slot='spiritRatio' slot-scope='t,r,index'>
                    <a-input placeholder='请输入带走比例' v-model='t'
                             suffix='%'
                             @input='e => spritCH(e,t,index)'
                             :disabled='disableSubmit || r.isSpirit && r.isSpirit == 1 ? false : true'></a-input>
                  </template>
                  <template slot='identifier' slot-scope='t,r,index'>
                    <a-input placeholder='请输入标识符' v-model='r.identifier'
                             @input='e => identifierCH(e,t,index)'
                             :disabled='disableSubmit || r.isSpirit && r.isSpirit == 1 ? false : true'></a-input>
                  </template>

                  <span slot='action' v-if='!disableSubmit' slot-scope='text, record,index'>
                        <a @click.stop="productDelete(index,'zpList')">删除</a>
                      </span>

                </a-table>
              </a-col>
            </div>
          </a-col>

          <!--          政策适用范围-->
          <a-col :span='24'>
            <div
              style='padding: 12px 24px;margin:12px 0;font-size: 16px;font-weight: 500;border-bottom: 1px solid #e8e8e8; border-top: 1px solid #e8e8e8'>
              政策适用范围
            </div>
          </a-col>

          <a-col :span='24'>
            <a-tabs default-active-key='1'>
              <a-tab-pane key='1' tab='部门'>
                <div style='padding:0 24px;'>
                  <a-col :md='16' :sm='24'>
                    <j-select-org v-if='!disableSubmit' selectButtonText='新增' :inputs='false' searchIcon=''
                                  @select='orgSelect' />
                    <div style='margin-bottom: 12px'></div>
                  </a-col>
                  <a-col :md='12' :sm='24'>
                    <a-table
                      ref='table'
                      size='middle'
                      class='Table'
                      bordered
                      rowKey='code'
                      :columns='orgColumns'
                      :dataSource='orgList'
                      :pagination='ipagination2'
                      :loading='loading'
                      @change="(e1,e2,e3) =>handleTableChange(e1,e2,e3,'3')"
                    >
                      <span slot='action' v-if='!disableSubmit' slot-scope='text, record,index'>
                        <a @click.stop='orgDeleta(index)'>删除</a>
                      </span>
                    </a-table>
                  </a-col>
                </div>
              </a-tab-pane>
              <a-tab-pane key='2' tab='经销商' force-render>
                <div style='padding:0 24px;'>
                  <a-col :md='16' :sm='24'>
                    <j-select-cust  v-if='!disableSubmit' selectButtonText='新增' :inputs='false'
                                    searchIcon='' @select='activeSelect' />
                    <div style='margin-bottom: 12px'></div>
                  </a-col>
                  <a-col :md='12' :sm='24'>
                    <a-table
                      ref='table'
                      size='middle'
                      class='Table'
                      bordered
                      rowKey='code'
                      :columns='custColumns'
                      :dataSource='custList'
                      :pagination='ipagination3'
                      :loading='loading'
                      @change="(e1,e2,e3) =>handleTableChange(e1,e2,e3,'4')"
                    >
                      <span slot='action' v-if='!disableSubmit' slot-scope='text, record,index'>
                        <a @click.stop='custDeleta(index)'>删除</a>
                      </span>
                    </a-table>
                  </a-col>
                </div>
              </a-tab-pane>
            </a-tabs>
          </a-col>

        </a-row>
      </a-form>
      <proChose ref='prochoose' @okbro='okbropro'></proChose>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction, postAction } from '@api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import CnMultiSelectTag from '@comp/dict/CnMultiSelectTag'
import { PageListMixin } from '@/mixins/PageListMixin'
import { ajaxGetDictItems, getDictItemsFromCache } from '@api/api'
import 'viewerjs/dist/viewer.css'
import { directive as viewer } from 'v-viewer'
import lodash from 'lodash'
import JSelectCust from '@/components/cn-select-popup/CnSelectCust'
import JSelectOrg from '@/components/cn-select-popup/JSelectOrg'
import JSelectProduct from '@/components/cn-select-popup/JSelectProduct'
import proChose from '@comp/cn-components/ProChose'

export default {
  name: 'templateModal',
  mixins: [PageListMixin],
  components: {
    proChose,
    CnMultiSelectTag,
    JSelectCust,
    JSelectOrg,
    JSelectProduct
  },

  data() {
    return {
      t1: 2,
      istodo: false,
      title: '新增',
      disabled: false,
      taskItemsList: [],
      custList: [],
      orgList: [],
      categoriesDetailVoList: [],
      custValue: '',

      bpList: [],
      zpList: [],
      bpColumns: [
        {
          title: '本品编号',
          align: 'center',
          dataIndex: 'code'
        },
        {
          title: '本品名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'left',
          width: 80,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }

      ],
      zpColumns: [
        {
          title: '赠品编号',
          align: 'center',
          dataIndex: 'code'
        },
        {
          title: '赠品名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '是否必带',
          align: 'center',
          dataIndex: 'isSpirit',
          scopedSlots: { customRender: 'isSpirit' }
        },
        {
          title: '带走比例',
          align: 'center',
          dataIndex: 'spiritRatio',
          scopedSlots: { customRender: 'spiritRatio' }
        },
        {
          title: '标识符',
          align: 'center',
          dataIndex: 'identifier',
          scopedSlots: { customRender: 'identifier' }
        },

        {
          title: '操作',
          dataIndex: 'action',
          align: 'left',
          width: 80,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }

      ],

      orgColumns: [
        {
          title: '组织编号',
          align: 'center',
          dataIndex: 'code'
        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'left',
          width: 80,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }

      ],
      custColumns: [
        {
          title: '经销商编号',
          align: 'center',
          dataIndex: 'code'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'left',
          width: 80,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }

      ],

      disableSubmit: false,
      areaLinkage: '',
      area: '',
      province: '',
      city: '',
      modal: {},
      areaData: '',
      proName: '产品',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      url: {
        add: window._CONFIG['domianActivitiURL'] + '/actPromotionController/saveOrUpdate'
      },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 分页参数 */
      ipagination1: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 分页参数 */
      ipagination2: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 分页参数 */
      ipagination3: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      }
    }
  },
  computed: {},
  watch: {},
  created() {

  },
  methods: {
    spritCH(e, e2, index) {
      console.log(e.target.value, e2, index)
      // identifier 标志符
      // spiritRatio 带走比例

      this.zpList[index].spiritRatio = e.target.value
      let a = 0
      let list =[]
      this.zpList.forEach(item =>{
        if(item.identifier&&item.identifier==this.zpList[index].identifier){
          item.spiritRatio = e.target.value
        }
        let k=list.findIndex(v=>v.identifier==item.identifier)
        if(k==-1||!item.identifier){
          list.push(item)
        }

      })
      console.log(list)
      list.forEach(item=>{
        let b = item.spiritRatio
        b ? b = b : b = 0
        a += b - 0
      })
      if(a >100){
        this.$message.info('输入的比例和不能大于100')
        if(this.zpList[index].identifier){
          this.zpList.forEach(item =>{
            if(item.identifier&&item.identifier==this.zpList[index].identifier){
              item.spiritRatio = undefined
            }
          })
        }else {
          this.zpList[index].spiritRatio = undefined
        }

      }
    },
    identifierCH(e, e2, index) {
      // identifier 标志符
      // spiritRatio 带走比例
      this.zpList[index].identifier = e.target.value
      let value= this.zpList.find(item=>item.identifier==e.target.value)
      if(value){
        this.zpList[index].spiritRatio=value.spiritRatio
      }
      let a = 0
      let list =[]
      this.zpList.forEach(item =>{
        let k=list.findIndex(v=>v.identifier==item.identifier)
        if(k==-1||!item.identifier){
          list.push(item)
        }
      })
      list.forEach(item=>{
        let b = item.spiritRatio
        b ? b = b : b = 0
        a += b - 0
      })
      if(a >100){
        this.$message.info('输入的比例和不能大于100')
        this.zpList[index].spiritRatio = undefined
      }
    },
    selectCH(e1, e2) {
      console.log(e1)
      this.zpList[e2].isSpirit = e1
      if(e1 == '0'){
        this.zpList[e2].spiritRatio = undefined
        this.zpList[e2].identifier = undefined
      }
    },
    goodsChange(e) {
      if (e == 1) {
        this.istodo = true
      } else if (e == 2) {
        this.istodo = false
      }
      console.log(e)
    },
    okbropro(e1, e2, e3) {
      this.form.setFieldsValue({
        productName: e1[0].maktx,
        productCode: e1[0].matnr
      })
      console.log(e1, e2, e3)
    },
    productSearch(status) {
      this.$refs.prochoose.rowKey = 'matnr'
      let formconfig = [
        {
          key: 'matnr',
          label: '商品编号'
        },
        {
          key: 'maktx',
          label: '商品名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '商品编号',
            align: 'center',
            dataIndex: 'matnr',
            width: 120,
            ellipsis: true
          },
          {
            title: '商品名称',
            align: 'center',
            dataIndex: 'maktx',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/cnProductController/getProductListByCust',
        multiple: false,
        columW: 11
      }
      this.name = '商品'
      this.$refs.prochoose.edit(formconfig, tableconfig, status)
    },
    productSelect(row, name, type) {
      row.map(v => {
        let index = this[name].findIndex(item => item.code == v.matnr)
        index == -1 && this[name].push({
          dateType: type,
          code: v.matnr,
          name: v.maktx,
          isSpirit: 0,
          spiritRatio: undefined,
          identifier:undefined
        })
      })
    },
    productDelete(index, name) {
      this[name].splice(index, 1)
    },


    tableColChange(e, key, r, index) {
      if (e instanceof Object) {
        e = e.target.value
      }
      this.categoriesDetailVoList[index][key] = e
    },
    activeSelect(row) {
      row.map(v => {
        let index = this['custList'].findIndex(item => item.code == v.erpCode)
        index == -1 && this['custList'].push({
          dateType: '4',
          code: v.erpCode,
          name: v.customerName
        })
      })
    },
    orgSelect(row) {
      row.map(v => {
        let index = this['orgList'].findIndex(item => item.code == v.orgCode)
        index == -1 && this['orgList'].push({
          dateType: '3',
          code: v.orgCode,
          name: v.orgName
        })
      })
    },

    custDeleta(index) {
      this.custList.splice(index, 1)
    },

    orgDeleta(index) {
      this.orgList.splice(index, 1)
    },

    add() {
      this.edit({})
    }
    ,
    edit(record) {
      this.form.resetFields()
      this.custList = []
      this.orgList = []
      this.bpList = []
      this.zpList = []
      this.categoriesDetailVoList = []
      this.model = Object.assign({}, record)
      this.visible = true
      record.isToDo == 1 ? this.istodo = true : this.istodo = false
      if (record.isFirst||record.isFirst===0) {
        this.$nextTick(() => {
          this.model.date = [this.model.startDate, this.model.endDate]
          this.categoriesDetailVoList = this.model.categoriesDetailVoList
          this.custList = this.model.detailVoList.filter(v => v.dateType == 4)
          this.orgList = this.model.detailVoList.filter(v => v.dateType == 3)
          this.bpList = this.model.detailVoList.filter(v => v.dateType == 1)
          this.zpList = this.model.detailVoList.filter(v => v.dateType == 2)
          this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
          // this.$set(this, 'taskItemsList', record.execRequires)
          // this.$set(this, 'taskItemsList1', record.writeOffRequires)
        })
      } else {

      }
    },
    close() {
      this.confirmLoading = false
      this.visible = false
    }
    ,
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          for (let i=0;i<this.zpList.length;i++){
            let item = this.zpList[i]
            if(item.isSpirit==1&&!item.spiritRatio&&!item.identifier){
              // debugger
              this.$message.warning('请输入带走比例和标识符')
              return
            }

          }
          that.confirmLoading = true
          let formData = { ...this.model, ...values }
          formData.detailVoList = [...this.custList, ...this.orgList, ...this.bpList, ...this.zpList]
          postAction(this.url.add, formData).then(res => {
            if (res.success) {
              that.$message.success(res.message)
              that.close()
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          })
        }
      })
    }
    ,
    handleCancel() {
      this.close()
    }
    ,
    changeJselect(name, value) {
      name = name.split('Code')
      if (name.length > 1) {
        name = name[0] + 'Name' + (name[1] ? name[1] : '')
        this.model[name] = value
        console.log(this.model)
      }
    },
    dateChange(date) {
      if (!date) {
        this.model.startDate = ''
        this.model.endDate = ''
        return
      }
      this.model.startDate = date[0]
      this.model.endDate = date[1]
    },
    selectRole(row, name, key) {
      console.log(row)
      let value = row.map(v => v[key])
      name = name.split('Code')
      if (name.length >= 1) {
        name = name[0] + 'Name' + (name[1] ? name[1] : '')
        this.model[name] = value + ''
      }
    },
    handleTableChange(pagination, filters, sorter, key) {
      console.log(pagination, filters, sorter, key)
      if (key == '1') {
        this.ipagination = pagination
      } else if (key == '2') {
        this.ipagination1 = pagination
      } else if (key == '3') {
        this.ipagination2 = pagination
      } else if (key == '4') {
        this.ipagination3 = pagination
      }
    }
  }
}
</script>

<style lang='less' scoped>
.items-title {
  padding: 12px 24px;
  margin: 12px 0;
  font-size: 16px;
  font-weight: 500;
  border-bottom: 1px solid #e8e8e8;
  border-top: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
}


.ant-transfer {
  width: 100%;
  display: flex !important;
  align-items: center;
}

.ant-transfer-operation {
  display: flex !important;
  flex-direction: column !important;
  align-items: center;
}

.file-box {
  position: relative;
  opacity: 1;
}

.file-btn {
  width: 100%;
  opacity: 0;
  position: absolute;
  z-index: 2;
  left: 0;
  top: 0;
  height: 100%;
}

.tableImages {
  width: 100%;
  opacity: 0;
  position: absolute;
  z-index: 2;
  left: 0;
  top: 0;
  height: 100%;
}

.areaAdd {
  width: 100%;
  display: flex;
  justify-content: space-between;

  .areaAdd-one {
    width: 40%;
    display: flex;
    flex-direction: column;
  }

  .areaAdd-mutiple {
    border: 1px solid black;
    width: 100%;
    min-height: 200px;
  }

  .contain-text {
    font-weight: 700;
    font-size: 18px;
  }
}

/deep/ .ant-modal-body {
  padding: 24px 0px;
}

/deep/ .ant-tabs-bar {
  padding-left: 24px;
}
</style>